/*
 * @Author: LiZhiWei
 * @Date: 2025-07-15 10:24:09
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-30 15:42:59
 * @Description:
 */

import { api, Http } from '#/api'

export function useLister(
  options: {
    entity?: string
    mode?: 'embed' | BaseFormMode
    noPage?: boolean
    type?: 'index' | 'trashed'
    url?: RequestUrl
  } = {
    mode: 'dialog',
    entity: '',
    noPage: false,
    type: 'index',
  }
) {
  const { entity = '', url, noPage, type = 'index' } = options
  // 列表相关状态
  const list = ref<any>([])
  const listLoading = ref(false)
  const columns = ref([])
  const statistic = ref({})

  const searchFormer = reactive({
    data: {},
    fields: [],
  })

  const pageFormer = reactive({
    page: 1,
    page_limit: 15,
    total: 0,
  })

  // 核心数据获取函数
  const fetch = (url: string, params: any) => {
    listLoading.value = true

    return Http.Get<any>(url, { params })
      .then((res) => {
        list.value = res.data
        columns.value = res.columns || []
        statistic.value = res.statistic ?? {}

        if (!noPage && res.meta) {
          pageFormer.total = res.meta.total
          pageFormer.page_limit = res.meta.per_page
        }

        if (
          Object.prototype.hasOwnProperty.call(res, 'form_widgets') &&
          searchFormer.fields.length === 0
        ) {
          searchFormer.fields = res.form_widgets
          searchFormer.data = {}
        }
        return res
      })
      .finally(() => {
        listLoading.value = false
      })
  }

  const afterFetched = (res: any, onFetched?: (res: any) => void) => {
    onFetched && onFetched(res)
  }

  // 默认的fetchData实现
  const fetchData = (onFetched?: (res: any) => void) => {
    const params = noPage
      ? { ...searchFormer.data, ...url?.params }
      : { ...pageFormer, ...searchFormer.data, ...url?.params }

    const requestUrl = type === 'trashed' ? api[entity].trashed : api[entity].index

    fetch(requestUrl, params).then((res) => {
      afterFetched(res, onFetched)
    })
  }

  // 自定义URL请求函数
  const fetchDataWith = (requestUrl: RequestUrl, onFetched?: (res: any) => void) => {
    const params = noPage
      ? { ...searchFormer.data, ...requestUrl.params }
      : { ...pageFormer, ...searchFormer.data, ...requestUrl.params }

    fetch(
      options.type === 'trashed' ? (requestUrl.trashed as string) : (requestUrl.index as string),
      params
    ).then((res) => {
      afterFetched(res, onFetched)
    })
  }

  // 更新列表项
  const updateListWithOne = (model: any, index: number) => {
    for (const key in list.value[index]) {
      if (Object.prototype.hasOwnProperty.call(model, key) && key !== 'id') {
        list.value[index][key] = model[key]
      }
    }
  }

  // 搜索框触发重新查询
  const handleSearchChange = (data: any) => {
    searchFormer.data = data
    pageFormer.page = 1
    fetchData()
  }

  // 自定义URL搜索
  const handleSearchChangeWith = (data: any, requestUrl: RequestUrl) => {
    searchFormer.data = data
    pageFormer.page = 1
    fetchDataWith(requestUrl)
  }

  // 路由导航函数
  const router = useRouter()
  const goCreatePage = (routeName?: string) => {
    router.push({ name: routeName ?? `${entity}Creator` })
  }
  const goEditPage = (id: number | string, routeName?: string) => {
    router.push({ name: routeName ?? `${entity}Editor`, params: { id } })
  }
  const goShowPage = (id: number | string, routeName?: string) => {
    router.push({ name: routeName ?? `${entity}Show`, params: { id } })
  }

  // 三元表达式与??的区别，?? 运算符在左侧值为 null 或 undefined 时才会返回右侧值，而三元运算符会返回左侧值。
  const getTrashedRoute = (routeName?: string) => {
    return routeName || `${entity}Trashed`
  }

  return {
    // 搜索相关
    searchFormer,
    pageFormer,
    handleSearchChange,
    handleSearchChangeWith,
    // 列表相关
    list,
    listLoading,
    columns,
    statistic,
    fetchData,
    fetchDataWith,
    goCreatePage,
    goEditPage,
    goShowPage,
    updateListWithOne,
    getTrashedRoute,
  }
}
